from django.db.models import Prefetch
from django.db.models import Q
from rest_framework import viewsets, status
from rest_framework.response import Response
from rest_framework.status import HTTP_400_BAD_REQUEST
from rest_framework.views import APIView

from .models import Inform, InformRead
from .serializers import InformSerializer, ReadInformSerializer


class InformViewSet(viewsets.ModelViewSet):
    queryset = Inform.objects.all()
    serializer_class = InformSerializer

    def get_queryset(self):
        queryset = self.queryset.select_related('author').prefetch_related(
            Prefetch("reads", queryset=InformRead.objects.filter(user_id=self.request.user.uid)), 'department').filter(
            Q(public=True) | Q(department=self.request.user.department) | Q(author=self.request.user)).distinct()
        return queryset


    # 定义destroy方法，用于删除对象
    def destroy(self, request, *args, **kwargs):
        # 获取要删除的对象
        instance = self.get_object()
        # 判断要删除的对象的作者是否为当前用户
        if instance.author.uid == request.user.uid:
            # 执行删除操作
            self.perform_destroy(instance)
            # 返回204状态码，表示删除成功
            return Response(status=status.HTTP_204_NO_CONTENT)
        else:
            return Response(status=status.HTTP_401_UNAUTHORIZED)

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        data = serializer.data
        data['read_count'] = InformRead.objects.filter(inform=instance).count()
        return Response(data=data)


class ReadInformView(APIView):
    def post(self, request):
        print(request.data)
        serializer = ReadInformSerializer(data=request.data)
        if serializer.is_valid():
            inform_pk = serializer.validated_data['inform_pk']
            if InformRead.objects.filter(inform_id=inform_pk, user_id=request.user.uid).exists():
                return Response()
            else:
                try:
                    InformRead.objects.create(inform_id=inform_pk, user_id=request.user.uid)
                except Exception:
                    return Response(data={'detail': '读取失败'}, status=HTTP_400_BAD_REQUEST)
                return Response()
        else:
            return Response(data={'detail': list(serializer.errors.values())[0][0]}, status=HTTP_400_BAD_REQUEST)
